import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;
import org.junit.Test;

import javax.lang.model.util.Elements;
import java.io.InputStream;
import java.util.List;

public class ParseXmlByDom4j {
    @Test
    public void testParseXml() throws Exception {
        //读取xml文件获取document对象
        SAXReader saxReader = new SAXReader();
        InputStream inputStream = ClassLoader.getSystemClassLoader().getResourceAsStream("mybatis-config.xml");
        Document document = saxReader.read(inputStream);
        //获取根节点configuration
        Element rootElement = document.getRootElement();
//        System.out.println(rootElement.getName());//configuration
        //获取environments标签以及default的值
        String xpath="/configuration/environments";
        Element environments = (Element) document.selectSingleNode(xpath);
        String defaultid = environments.attributeValue("default");
        System.out.println(defaultid);
        //获取environment标签
//        Element environment = (Element)environments.selectSingleNode("environment");
        Element environmentelm = (Element) document.selectSingleNode("/configuration/environments/environment[@id='" + defaultid + "']");
        //获取数据源类型和事务管理类型
        Element dataSource = environmentelm.element("dataSource");
        Element TransactionManager = environmentelm.element("transactionManager");
//        System.out.println(dataSource.attributeValue("type"));
//        System.out.println(TransactionManager.attributeValue("type"));
        List <Element> elements = dataSource.elements();
        elements.forEach(property -> {
            System.out.println(property.attributeValue("name") + "=" + property.attributeValue("value"));
        });
        Element  mappers = (Element ) document.selectSingleNode("/configuration/mappers");
        List <Element> mapper = mappers.elements();
        mapper.forEach(map -> {
            System.out.println(map.attributeValue("resource"));
        });
        /*解析sqlMapper.xml*/
        InputStream inputStream1 = ClassLoader.getSystemClassLoader().getResourceAsStream("CarMapper.xml");
        Document document1 = saxReader.read(inputStream1);
        String xpathmapper ="/mapper";
        Element mapper1 = (Element) document1.selectSingleNode(xpathmapper);
        String namespace = mapper1.attributeValue("namespace");
        System.out.println(namespace);
        List <Element> cruds = mapper1.elements();
        cruds.forEach(crud -> {
            String id = crud.attributeValue("id");
            String resultType = crud.attributeValue("resultType");
            String sql = crud.getTextTrim();
            String sqls = sql.replaceAll("#\\{[0-9a-zA-Z_$]*}", "?");
            System.out.println("id:" + id + "  resultType:" + resultType + "  sql:" + sqls);
        });

    }
}
